<template>
  <Layout class="template-layout">
    <!-- 顶部布局 -->
    <Header>
      <zz-Search
        :searchOptions="searchOptions"
        @getSearchData="getSearchData"
        @resetFields="resetFields"
      ></zz-Search>
    </Header>
    <!-- 内容区 -->
    <Content>
      <zz-PageBars>
        <template #buttons>
          <Button
            type="primary"
            size="default"
            @click="add"
            :loading="btnLoading"
            >新增</Button
          >
          <Button
            type="error"
            size="default"
            ghost
            @click="delBatch"
            :loading="btnLoading"
            >删除</Button
          >
          <Button size="default" @click="importM">导入</Button>
          <Button size="default" @click="exportM">导出</Button>
        </template>
      </zz-PageBars>
      <zz-Table
        ref="zzTable"
        :data="tableData"
        :hasPage="true"
        :page="tablePage"
        :loading="loading"
        @pageChange="pageChange"
      >
        <vxe-column
          type="checkbox"
          title=""
          fixed="left"
          width="40"
        ></vxe-column>
        <vxe-column
          type="seq"
          title="序号"
          fixed="left"
          width="50"
        ></vxe-column>
        <vxe-column
          field="userCode"
          title="用户编码"
          fixed="left"
          :min-width="120"
        >
          <template #default="{ row }">
            <a @click="dealUser(row)">{{ row.userCode }}</a>
          </template>
        </vxe-column>
        <vxe-column
          field="userName"
          title="用户姓名"
          fixed="left"
          :min-width="120"
        ></vxe-column>
        <vxe-column field="isEffective" title="是否生效" :min-width="120">
          <template v-slot="{ row }">
            <Switch
              v-model="row.status"
              true-value="1"
              false-value="0"
              :disabled="row.disabled"
              @on-change="changeInvalid(row)"
            />
          </template>
        </vxe-column>
        <vxe-column field="status" title="状态" :min-width="120">
          <template v-slot="{ row }">
            <span
              v-if="row.status === '1'"
              style="
                display: inline-block;
                padding-right: 5px;
                padding-left: 5px;
                border-radius: 4px;
                border: 1px solid #19be6b;
                color: #19be6b;
              "
            >
              已生效
            </span>
            <span
              v-else
              style="
                display: inline-block;
                padding-right: 5px;
                padding-left: 5px;
                border-radius: 4px;
                border: 1px solid #ed4014;
                color: #ed4014;
              "
            >
              已失效
            </span>
          </template>
        </vxe-column>
        <vxe-column
          field="useSys"
          title="使用系统"
          :min-width="120"
          :formatter="formatYn"
        >
        </vxe-column>
        <vxe-column
          field="telephone"
          title="手机号码"
          :min-width="120"
        ></vxe-column>
        <vxe-column
          field="role"
          title="角色"
          :min-width="150"
          show-overflow="tooltip"
        >
        </vxe-column>
        <vxe-column field="sex" title="性别" :min-width="120">
          <template v-slot="{ row }">
            <Image
              src="src/assets/png/man.png"
              fit="fit"
              width="18px"
              height="18px"
              v-if="row.sex === '1'"
            />
            <Image
              src="src/assets/png/woman.png"
              fit="fit"
              width="18px"
              height="18px"
              v-else
            />
          </template>
        </vxe-column>
        <vxe-column
          field="birthDay"
          title="出生日期"
          :min-width="120"
          :formatter="formatDate"
        ></vxe-column>
        <vxe-column field="address" title="地址" :min-width="150"></vxe-column>
        <vxe-column
          field="lastLoginTime"
          title="最后登录时间"
          :min-width="150"
          :formatter="formatTime"
        ></vxe-column>
        <vxe-column
          field="createDate"
          title="创建日期"
          :min-width="120"
          :formatter="formatDate"
        ></vxe-column>
        <vxe-column title="操作" :min-width="180" fixed="right" align="center">
          <template v-slot="{ row }">
            <zz-TableBtn
              type="text"
              :loading="btnLoading"
              @click="empowerment(row)"
              :disabled="row.disabled"
              >赋权</zz-TableBtn
            >
            <Dropdown @on-click="clickMore($event, row)" transfer>
              <zz-TableBtn type="text">
                更多
                <Icon type="ios-arrow-down"></Icon>
              </zz-TableBtn>
              <template #list>
                <DropdownMenu>
                  <DropdownItem name="bind">绑定账号</DropdownItem>
                  <DropdownItem name="resetPassword">重置密码</DropdownItem>
                </DropdownMenu>
              </template>
            </Dropdown>
          </template>
        </vxe-column>
      </zz-Table>
    </Content>
    <add-user ref="addUser" @query="query"></add-user>
    <edit-user ref="editUser" @query="query"></edit-user>
    <empower ref="empower" @query="query"></empower>
    <zz-Emport
      ref="zzEmport"
      :titles="emportTitleNames"
      :fileds="emportTitleFields"
      :tablePage="tablePage"
      :urlObj="$API.userManagement.user.exportData"
      :defaultFileName="'用户信息表'"
    ></zz-Emport>
    <zz-Import
      ref="zzImport"
      :tmplId="'98063e8f-6b18-15f7-21f1-27d7086944a4'"
      :uploadUrl="'excel/pre-import-excel-with-type'"
      :saveUrl="'excel/save-excel'"
      :downFileName="'用户信息表下载模版'"
      @success="importSuccess"
    ></zz-Import>
  </Layout>
</template>

<script>
import faker from 'faker'
import addUser from './components/addUser.vue'
import editUser from './components/editUser.vue'
import empower from './components/empower.vue'
export default {
  name: 'userManagement',
  emits: ['query'],
  components: { addUser, editUser, empower },
  data() {
    return {
      // model
      model: {
        userCode: '',
        userName: '',
        roleId: '',
        sex: '',
        loginAccount: '',
      },
      // list
      emportTitleNames: [
        '用户编码',
        '用户名称',
        '手机号码',
        '角色',
        '性别',
        '出生日期',
        '年龄',
        '地址',
        '毕业院校',
        '学历',
        '专业',
        '公司编码',
        '部门编码',
        '职务',
        '职称',
      ],
      emportTitleFields: [
        'userCode',
        'userName',
        'telephone',
        'role',
        'sex',
        'birthDay',
        'age',
        'address',
        'school',
        'education',
        'major',
        'companyCode',
        'departmentCode',
        'jobPost',
        'jobTitle',
      ],
      // 页面显示相关
      loading: false,
      btnLoading: false,
      tableData: [],
      tablePage: {
        pageNum: 1,
        pageSize: 15,
        total: 0,
      },
      // 业务相关
      roleList: [],
      sexList: [],
    }
  },
  computed: {
    searchOptions() {
      return {
        // 接收字段
        model: this.model,
        // 配置表单
        column: [
          {
            label: '用户编码',
            type: 'inputText',
            field: 'userCode',
          },
          {
            label: '用户姓名',
            type: 'inputText',
            field: 'userName',
          },
          {
            label: '用户角色',
            type: 'treeSelect',
            field: 'roleId',
            option: this.roleList,
          },
          {
            label: '用户性别',
            type: 'selectBase',
            field: 'sex',
            option: this.sexList,
          },
          {
            label: '登录账号',
            type: 'inputText',
            field: 'loginAccount',
          },
        ],
      }
    },
  },
  async created() {
    await this.init()
    this.query('search')
  },
  methods: {
    // 初始化
    async init() {
      this.sexList = [
        { value: '1', label: '男' },
        { value: '0', label: '女' },
      ]
      this.roleList = await this.getRoleInfo()
    },
    // 获取当前用户涉及的角色信息
    async getRoleInfo() {
      let res = await this.$API.roleManagement.role.queryAllWithRight.get()
      if (res.code !== '01') {
        return []
      } else {
        // 将列表转成树
        res.data.forEach((e) => {
          e.title = e.roleName
          e.selected = false
          e.checked = false
        })
        let roleList = this.$XEUtils.toArrayTree(res.data, {
          key: 'roleId',
        })
        return roleList
      }
    },
    // 查询按钮
    getSearchData(searchData) {
      this.model = searchData
      this.query('search')
    },
    // 查询
    async query(mode) {
      this.loading = true
      if (mode === 'search') {
        this.model.queryParam = {
          pageNum: 1,
          pageSize: 15,
          total: 0,
        }
      }
      let param = {
        ...this.model,
        roleIds: [],
      }
      if (this.$TOOL.isNotEmpty(this.model.roleId)) {
        param['roleIds'].push(this.model.roleId)
      }
      let res = await this.$API.userManagement.user.queryWithPage.post(param)
      if (res.code === '01') {
        this.tableData = res.bizList
        let userInfo = JSON.parse(this.$TOOL.session.get('userInfo'))
        this.tableData.forEach((user) => {
          if (userInfo.userId == user.userId) {
            user.disabled = true
          }
        })
        this.tablePage.total = res.total
        this.tablePage.pageSize = res.pageSize
        this.loading = false
      } else {
        this.loading = false
      }
    },

    // 新增
    add() {
      this.$refs.addUser.modelIsOpen = true
    },
    // 删除
    delBatch() {
      let arr = this.$refs.zzTable.getCheckboxRecords()
      // 校验
      if (arr.length === 0) {
        this.$Message.warning('请选择要删除的数据')
        return
      }
      let userInfo = JSON.parse(this.$TOOL.session.get('userInfo'))
      let findUser = arr.find((user) => userInfo.userId == user.userId)
      if (findUser) {
        this.$Message.warning('还想“扇”自己？别闹！')
        return
      }
      let ids = arr.map((e) => e.userId)
      this.$Modal.confirm({
        title: '确认',
        content: '确定要删除吗？',
        onOk: async () => {
          let res = await this.$API.userManagement.user.deleteBatch.post(ids)
          if (res.code === '01') {
            this.$Message.success('删除成功')
            this.query('search')
          } else {
            this.$Message.error('删除失败')
          }
        },
      })
    },
    // 导出
    async exportM() {
      this.$refs.zzEmport.modelIsOpen = true
    },
    // 导入
    async importM() {
      this.$refs.zzImport.modelIsOpen = true
    },
    importSuccess() {
      this.query()
    },
    // 查看or编辑
    dealUser(row) {
      let userId = row.userId
      this.$refs.editUser.userId = userId
      this.$refs.editUser.value = true
    },
    // 赋权
    async empowerment(row) {
      row.failureTime = new Date(row.failureTime)
      this.$TOOL.assionValues(row, this.$refs.empower.model)
      this.$refs.empower.useSys = row.useSys === '0' ? false : true
      this.$refs.empower.modelIsOpen = true
    },
    // 更多
    clickMore(val, row) {
      if (val && val === 'resetPassword') {
        this.resetPassword(row.userId)
      } else if (val && val === 'bind') {
        this.$Message.warning('该功能未开发，敬请期待')
      }
    },
    // 重置密码
    resetPassword(id) {
      this.$Modal.confirm({
        title: '确认',
        content: '重置后不可恢复，确定要重置密码吗？',
        onOk: async () => {
          let res = await this.$API.userManagement.user.resetPassword.get(id)
          if (res.code === '01') {
            this.$Message.success('重置密码成功')
          } else {
            this.$Message.error('重置密码失败')
          }
        },
      })
    },
    // 更改失效状态
    async changeInvalid(row) {
      let res = await this.$API.userManagement.user.changeInvalid.get(
        row.userId
      )
      if (res.code === '01') {
        this.query()
      } else {
        this.$Message.error('系统错误，请联系管理员')
        this.query()
      }
    },
    // 格式化
    formatDate({ cellValue }) {
      return this.$TOOL.format.formatDate(cellValue)
    },
    formatTime({ cellValue }) {
      return this.$TOOL.format.formatTime(cellValue)
    },
    formatYn({ cellValue }) {
      return cellValue == '1' ? '是' : '否'
    },
    // 分页
    pageChange(page) {
      this.model.queryParam.pageNum = page.currentPage
      this.model.queryParam.pageSize = page.pageSize
      this.query()
    },
    // 获取假数据
    getFakeDate() {
      faker.locale = 'zh_CN'
      let users = []

      for (let i = 0; i < 15; i++) {
        let user = {
          userCode: faker.random.number(),
          userName: faker.name.findName(),
          telephone: faker.phone.phoneNumber(),
          role: faker.random.arrayElement(['Admin', 'User']),
          sex: faker.random.arrayElement(['1', '0']),
          birthDay: faker.date.past().getTime(),
          address: faker.address.streetAddress(),
          status: faker.random.arrayElement(['1', '0']),
          isInvalid: faker.random.boolean(),
          lastLoginTime: faker.date.recent().getTime(),
          createDate: faker.date.past().getTime(),
        }

        users.push(user)
      }
      return users
    },
    // 重置
    resetFields() {},
  },
}
</script>

<style></style>
